<template>
  <div class="parent">
    <img class="logoImage" src="../../assets/Logo/logo.png" alt="暂无图片" @click="router.push('/')">
    <el-text class="logoText">注册</el-text>
    <el-text class="logoText1" size="default">已有账号？</el-text>
    <el-text class="loginText" @click="toLogin">马上登录</el-text>
    <el-card class='registerCard'>
      <div class="image-content">
        <el-form :model="user" label-width="auto" style="max-width: 600px" :rules="rules" ref="formRef">
          <el-form-item prop="account">
            <el-input class="registerInput" maxlength="11" v-model="user.account" type="text" size="large" placeholder="手机"/>
          </el-form-item>
          <el-form-item prop="code">
            <el-input class="registerInput" maxlength="6" type="text" size="large" v-model="user.code" style="margin-bottom: 20px;" placeholder="验证码">
              <template #suffix>
                |&nbsp;<el-button class="custom-suffix" @click="send_sms">{{ user.sms_btn_text1 }}</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input class="registerInput" maxlength="16" type="password"  v-model="user.password"size="large" show-password placeholder="密&nbsp;&nbsp;&nbsp;&nbsp;码"/>
          </el-form-item>
          <el-form-item>
            <el-checkbox class="check_color" size="small" @change="is_check"><el-text size="small">我已阅读并接受丁香园《<a href="">用户协议</a>》《<a href="">隐私政策</a>》</el-text></el-checkbox>
            <el-button color="#7753ff" size="large" style="width: 100%;margin-top: 10px;border-radius: 20px 20px 20px 20px;" @click="Register">注册</el-button>
          </el-form-item>
        </el-form>
        <div style="margin-top: 5%; margin-left: 40%; ">
          <el-text style="color: #7753ff;" @click="">使用邮箱注册</el-text>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, watch} from "vue";
import user from "../../api/user"
import { ElMessage } from "element-plus";
import {useRouter} from "vue-router";
import {useStore} from "vuex";
const router = useRouter()
const store = useStore()
let activeName = ref('first')

let inputValue = ref(false)

let is_check_info =ref(false)
const is_check=(info)=>{
  is_check_info.value = info
}

// 侦视属性，监听属性
watch(
    () => user.account,
    () => {
      if(/^1[3-9]\d{9}$/.test(user.account)){
        // 发送ajax验证手机号是否已经注册
        user.check_mobile().then((result) => {
          // ElMessage.info(result.data.message);
          ElMessage({
            message: result.data.message,
            type: 'success',
          })
        })
            .catch(error=>{
              console.log(error);
              ElMessage.error(error.response.data.message);
            })
      }
    })

const formRef = ref(null);

// 注册手机号等校验
const rules = {
  account: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确格式的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
};

// 自定义校验函数
function validatePassword(rule, value, callback) {
  if (value.length < 8 || value.length > 16) {
    return callback(new Error('密码长度必须在8到16位之间'));
  }
  const regex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z\d]).+$/;
  if (!regex.test(value)) {
    return callback(new Error('密码必须包含字母、数字和特殊字符'));
  }
  callback();
}

const Register = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 发送请求
      user.register().then(response=>{

        console.log('-----注册成功----');
        console.log(response);

        // 注册成功！
        // 先删除从前的登录状态
        localStorage.removeItem("refresh_token");
        localStorage.removeItem("access_token");
        sessionStorage.removeItem("refresh_token");
        sessionStorage.removeItem("access_token");

        sessionStorage.setItem("refresh_token", response.data.refresh);
        sessionStorage.setItem("access_token", response.data.token);

        // 把用户登录的载荷信息，保存到vuex中
        let payload = response.data.data.token.split(".")[1]  // 载荷
        let payload_data = JSON.parse(atob(payload)) // 用户信息

        store.commit("login", payload_data)
        ElMessage.success("注册成功！");

        user.reset();
        // 目前我们没有完成用户中心，所以先跳转到首页
        router.push("/");
      }).catch(error=>{
        // 注册失败！
        console.log('-----注册失败----');
        console.log(error);
        ElMessage.success(`用户注册失败！错误信息：${error?.response?.data?.message}`);
      })
    } else {
      ElMessage.error('输入有误，注册失败！');
      return false;
    }
  });
};

// ^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,}$

// 发送短信
const send_sms = ()=> {
  console.log("是否选中："+is_check_info.value)
  if (is_check_info.value === false) {
    ElMessage.error("请勾选用户协议！")
    return false
  }

  if (!/1[3-9]\d{9}/.test(user.account)) {
    ElMessage.error("手机号格式有误！")
    return false
  }

  // 判断是否处于短信发送的冷却状态
  if (user.is_send) {
    ElMessage.error("短信发送过于频繁！")
    return false
  }

  let time = user.sms_interval;

  // 发送短信请求
  user.register_send_sms().then(response=>{
    ElMessage.success("短信发送中，请留意您的手机！");
    // 发送短信后进入冷却状态
    user.is_send = true;
    // 冷却倒计时
    clearInterval(user.interval);
    user.interval = setInterval(()=> {
      if (time < 1) {
        user.is_send = false  // 退出短信发送的冷却状态
        user.sms_btn_text1 = "点击获取验证码"
      } else {
        time -= 1;
        user.sms_btn_text1 = `${time}秒后重新获取`;
      }
    },1000)
  }).catch(error=>{
    console.log(error);

    ElMessage.error(error?.response?.data?.message);
    time = error?.response?.data?.interval;
    // 冷却倒计时
    clearInterval(user.interval);
    user.interval = setInterval(()=>{
      if(time<1){
        // 退出短信发送的冷却状态
        user.is_send = false
        user.sms_btn_text1 = "点击获取验证码"
      }else{
        user.is_send = true;
        time-=1;
        user.sms_btn_text1 = `${time}秒后重新获取`;
      }
    }, 1000)

  })
}

const toLogin=()=>{
  router.push('/login')
}




</script>

<style scoped>
.logoImage{
  position: absolute;
  top: 10%;
  left: 22%;
  display:flex;
  width: 150px;
  height: 80px;
  transform: translate(-50%, -50%);
}

.logoText{
  position: absolute;
  top: 10%;
  left: 30%;
  display:flex;
  transform: translate(-50%, -50%);
  font-size: 25px;
  color: black;
}

.logoText1{
  position: absolute;
  top: 10%;
  right: 18%;
  display:flex;
  transform: translate(-50%, -50%);
}

.loginText{
  position: absolute;
  top: 10%;
  right: 15%;
  display:flex;
  transform: translate(-50%, -50%);
  color: #7753ff;
}


.registerCard{
  position: absolute;
  top: 55%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 68%;
  height: 80%;
  border-radius: 8px;

}



.image-content {
  margin: auto;
  width: 40%;
}


.registerInput >>> .el-input__wrapper {
  width: 80%;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 20px 20px 20px 20px; /* 这里的20px可以根据需要修改成任何你想要的大小 */
  background-color: rgba(248, 248, 248);
}

.registerInput >>> .el-input__inner {
  /*background-color: rgba(0, 0, 0, 0.1);*/
}



.custom-suffix {
  display: flex;
  align-items: center;
  padding-right: 10px;
  color: #7753ff;
  border: none;
  background-color: rgba(0, 0, 0, 0);
}
</style>